#include <dockView.h>

namespace View {
  
  DockView::DockView(GooCanvasItem *newRoot)
    :root(goo_canvas_group_new(newRoot,NULL))
  {
    ViewConf *conf = ViewConf::GetViewConf();
    gdouble mainWindowLength(conf->GetDoubleData("mainWindowLength")),
      mainWindowHeigth(conf->GetDoubleData("mainWindowHeigth")),
      dockIconLength(conf->GetDoubleData("dockIconLength")),
      dockIconHeigth(conf->GetDoubleData("dockIconHeigth"));

    coordinatesX = mainWindowLength/2.0 ;
    coordinatesY = mainWindowHeigth - dockIconHeigth ;
    dockIconWidth = dockIconLength;

    AddDockIcon(Model::SYSTEM_SETTING);
  }
  
  DockView::~DockView()
  {
    std::map<Model::AttackType,DockIcon *>::iterator it;
    for ( it=dockIcons.begin() ; it != dockIcons.end(); it++ ){
      delete (*it).second;
      (*it).second = NULL;
    }
    goo_canvas_item_remove(root);
  }

  bool DockView::RePositioning()
  {
    std::map<Model::AttackType,DockIcon *>::iterator it;
    gdouble dockIconCoordinateX = coordinatesX  - dockIcons.size() * ( dockIconWidth  / 2.0 );
    for ( it=dockIcons.begin() ; it != dockIcons.end(); it++ ){
      (*it).second->MoveTo(dockIconCoordinateX ,  coordinatesY);
      dockIconCoordinateX += dockIconWidth  ;
    }
    while(gtk_events_pending())
      gtk_main_iteration();
    return true;
  }
  
  bool DockView::AddDockIcon(Model::AttackType attackType)
  {
    if(NULL != dockIcons[attackType])
      return false;
    Controller::AllFactory factory ;
    DockIcon *newIcon = factory.CreateDockIcon(attackType,root);
    if(NULL != newIcon){
      dockIcons[attackType] = newIcon;
      RePositioning();
    }
    return true;
  }

  bool DockView::DelDockIcon(Model::AttackType attackType)
  {
    delete dockIcons[attackType];
    dockIcons.erase(attackType);
    RePositioning();
    return true;
  }

  bool DockView::ReceiveBroadcast(Controller::Broadcast *broadcast)
  {
    //    std::cout<<"DockView::ReceiveBroadcast(Controller::Broadcast *broadcast)\n";
    if(Controller::BROADCAST_TYPE_ONSHOW_ATTACKS == broadcast->GetBroadcastType()){
      int onshowAttacks = broadcast->GetDoubleData();
      onshowAttacks >>= 1;
      if(onshowAttacks & 1)
	AddDockIcon(Model::SYN_ATTACK);
      else
	DelDockIcon(Model::SYN_ATTACK);
      onshowAttacks >>= 1;
      if(onshowAttacks & 1)
	AddDockIcon(Model::ARP_ATTACK);
      else
	DelDockIcon(Model::ARP_ATTACK);
      onshowAttacks >>= 1;
      if(onshowAttacks & 1)
        AddDockIcon(Model::SMURF_ATTACK);
      else
        DelDockIcon(Model::SMURF_ATTACK);
    }
    return true;
  }
  
}
